package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.DateUtil;
import com.haoze.common.utils.HttpClientUtil;
import com.haoze.nurseapp.aop.NurseLogAop;
import com.haoze.nurseapp.dao.HelperMapper;
import com.haoze.nurseapp.dao.PatientInHospitalMapper;
import com.haoze.nurseapp.dto.HelpItemParamDTO;
import com.haoze.nurseapp.enumeration.HelpItemEnum;
import com.haoze.nurseapp.service.HelperService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@Service
public class HelperServiceImpl implements HelperService {
    @Autowired
    PatientInHospitalMapper patientInHospitalMapper;
    @Autowired
    HelperMapper helperMapper;
    @Value("${his.url.query}")
    private String hisQueryUrl;

    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);

    @Override
    public Result queryHisItemDicts(String hisDictName) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        String empNo = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        if(StringUtils.isNotBlank(empNo)) {
            String operationDate = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
            String params = "{" +
                    "    'operationID': '" + ConstantEnum.HZQUERY_10014.getKey() + "'," +
                    "    'c_request': {" +
                    "        'request': {" +
                    "            'operator': '" + empNo + "'," +
                    "            'operationdate': '" + operationDate + "'," +
                    "            'hospital_no': '01'," +
                    "            'source': '3'," +
                    "            'patsource': '1'," +
                    "            'dict_name': '" + hisDictName + "'," +
                    "        }" +
                    "    }" +
                    "}";
            log.info("操作码:{}-{}", ConstantEnum.HZQUERY_10014.getKey(), params);
            String resultString = HttpClientUtil.sendPostByJson(hisQueryUrl, params);
            log.info("操作码:{}-result-{}", ConstantEnum.HZQUERY_10014.getKey(), resultString);
            JSONObject jsonObject = JSONObject.parseObject(resultString);
            if (!jsonObject.getString("Error_Id").equals(ConstantEnum.HIS_ERROR_CODE_1.getKey())) {
                return ResultGenerator.genFailedResult("操作出错：" + jsonObject.getString("Error_Msg"));
            }
            JSONArray list = jsonObject.getJSONObject("c_response").getJSONObject("response").getJSONArray("waitpat");
            if (list == null || list.size() == 0) {
                list = jsonObject.getJSONObject("c_response").getJSONObject("response").getJSONArray("list");
            }
            return ResultGenerator.genOkResult(list);
        }else{
            return ResultGenerator.genOkResult();
        }
    }


    @Override
    public Result queryItemDicts(HelpItemParamDTO helpItemParam) {
        if (StringUtils.isBlank(helpItemParam.getItemClassName())) {
            return ResultGenerator.genFailedResult("项目类型不能为空");
        }
        String deptId = helpItemParam.getDeptId();
        String search = helpItemParam.getQueryString();
        Integer page = helpItemParam.getPage();
        Integer pageSize = helpItemParam.getPageSize();
        String type = helpItemParam.getType();
        List<String> selectIds = helpItemParam.getDataIds();
        String levelId = StringUtils.isBlank(helpItemParam.getLevelId()) ? "" : helpItemParam.getLevelId();

        // type 0 科室，1其他（如检查，检验，处置项目）
        HelpItemEnum helpItemEnum = HelpItemEnum.getHelpByName(helpItemParam.getItemClassName());
        switch (helpItemEnum) {
            case ITEM_CLASS_EXAM:
            case ITEM_CLASS_LAB:
            case ITEM_CLASS_MANAGEMENT:
                return queryExamItemDepts(deptId, search, helpItemEnum.getEnumCtlId(), page, pageSize, type, selectIds);
            case ITEM_CLASS_MATERIAL:
                return queryMaterialItemDicts(search, page, pageSize, selectIds);
            case ITEM_CLASS_OPER:
                return queryOperItemDicts(search, page, pageSize, selectIds, levelId);
            case ITEM_CLASS_DRUG:
                return queryDrugItemDicts(search, page, pageSize, selectIds);
            default:break;
        }
        return null;
    }

    private Result queryExamItemDepts(String deptId, String search, String itemClassId, Integer page, Integer pageSize, String type, List<String> selectIds) {
        PageHelper.startPage(page, pageSize);
        if (type.equals("0")) { // 查询检查科室
            return ResultGenerator.genOkResult(PageInfo.of(helperMapper.queryExamItemDepts(search, itemClassId, selectIds)));
        } else { // 查询检查项目
            return ResultGenerator.genOkResult(PageInfo.of(helperMapper.queryExamItems(search, itemClassId, selectIds, deptId)));
        }
    }

    private Result queryOperItemDicts(String search, Integer page, Integer pageSize, List<String> selectIds, String levelId) {
        PageHelper.startPage(page, pageSize);
        return ResultGenerator.genOkResult(PageInfo.of(helperMapper.queryOperItems(search, selectIds, levelId)));
    }

    private Result queryMaterialItemDicts(String search, Integer page, Integer pageSize, List<String> selectIds) {
        PageHelper.startPage(page, pageSize);
        return ResultGenerator.genOkResult(PageInfo.of(helperMapper.queryMaterialItems(search, selectIds)));
    }

    private Result queryDrugItemDicts(String search, Integer page, Integer pageSize, List<String> selectIds) {
        PageHelper.startPage(page, pageSize);
        return ResultGenerator.genOkResult(PageInfo.of(helperMapper.queryDrugItems(search, selectIds)));
    }


    @Override
    public Result queryHelpDrugItems(String phamStdCode, String phamForm, String illnessCode, String secretCode, String toxicologyProperty, Integer page, Integer pageSize) {
        int totalLength = 0;
        List<Object> collect = new CopyOnWriteArrayList<>();
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        String empNo = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        if(StringUtils.isNotBlank(empNo)) {
            String operationDate = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
            String params = "{" +
                    "    'operationID': '" + ConstantEnum.HZQUERY_10012.getKey() + "'," +
                    "    'c_request': {" +
                    "        'request': {" +
                    "            'operator': '" + empNo + "'," +
                    "            'operationdate': '" + operationDate + "'," +
                    "            'hospital_no': '02'," +
                    "            'source': '3'," +
                    "            'pham_form': '" + phamForm + "'," +
                    "            'illness_code': '" + illnessCode + "'," +
                    "            'secret_code': '" + secretCode + "'," +
                    "            'toxicology_property': '" + toxicologyProperty + "'," +
                    "            'pham_std_code': '" + phamStdCode + "'," +
                    "        }" +
                    "    }" +
                    "}";
            log.info("操作码:{}-{}", ConstantEnum.HZQUERY_10012.getKey(), params);
            String resultString = HttpClientUtil.sendPostByJson(hisQueryUrl, params);
            log.info("操作码:{}-result-{}", ConstantEnum.HZQUERY_10012.getKey(), resultString);
            JSONObject jsonObject = JSONObject.parseObject(resultString);
            if (!jsonObject.getString("Error_Id").equals(ConstantEnum.HIS_ERROR_CODE_1.getKey())) {
                return ResultGenerator.genFailedResult("操作出错：" + jsonObject.getString("Error_Msg"));
            }

            JSONArray list = jsonObject.getJSONObject("c_response").getJSONObject("response").getJSONArray("waitpat");
            if (list == null || list.size() == 0) {
                list = jsonObject.getJSONObject("c_response").getJSONObject("response").getJSONArray("list");
            }else{
                totalLength = list.size();
                if (page != 0 && pageSize != 0) {
                    collect = list.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
                }
            }
            PageInfo<Object> pageInfo = new PageInfo<>(collect);
            pageInfo.setTotal(totalLength);
            return ResultGenerator.genOkResult(pageInfo);
        }else{
            PageInfo<Object> pageInfo = new PageInfo<>(collect);
            pageInfo.setTotal(totalLength);
            return ResultGenerator.genOkResult(pageInfo);
        }
    }


    @Override
    public Result queryHelpMaterialItems(String itemCode, String itemTypeId, String secretCode, String expSx, String outWh, Integer page, Integer pageSize) {
        int totalLength = 0;
        List<Object> collect = new CopyOnWriteArrayList<>();
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        String empNo = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        if(StringUtils.isNotBlank(empNo)) {
            String operationDate = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");

            String params = "{" +
                    "    'operationID': '" + ConstantEnum.HZQUERY_10013.getKey() + "'," +
                    "    'c_request': {" +
                    "        'request': {" +
                    "            'operator': '" + empNo + "'," +
                    "            'operationdate': '" + operationDate + "'," +
                    "            'hospital_no': '02'," +
                    "            'source': '3'," +
                    "            'item_type_id': '" + itemTypeId + "'," +
                    "            'secret_code': '" + secretCode + "'," +
                    "            'exp_sx': '" + expSx + "'," +
                    "            'out_wh': '" + outWh + "'," +
                    "            'item_code': '" + itemCode + "'," +
                    "        }" +
                    "    }" +
                    "}";
            log.info("操作码:{}-{}", ConstantEnum.HZQUERY_10013.getKey(), params);
            String resultString = HttpClientUtil.sendPostByJson(hisQueryUrl, params);
            log.info("操作码:{}-result-{}", ConstantEnum.HZQUERY_10013.getKey(), resultString);
            JSONObject jsonObject = JSONObject.parseObject(resultString);
            if (!jsonObject.getString("Error_Id").equals(ConstantEnum.HIS_ERROR_CODE_1.getKey())) {
                return ResultGenerator.genFailedResult("操作出错：" + jsonObject.getString("Error_Msg"));
            }
            JSONArray list = jsonObject.getJSONObject("c_response").getJSONObject("response").getJSONArray("waitpat");
            if (list == null || list.size() == 0) {
                list = jsonObject.getJSONObject("c_response").getJSONObject("response").getJSONArray("list");
            }else{
                totalLength = list.size();
                if (page != 0 && pageSize != 0) {
                    collect = list.stream().skip((page - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
                }
            }
            PageInfo<Object> pageInfo = new PageInfo<>(collect);
            pageInfo.setTotal(totalLength);
            return ResultGenerator.genOkResult(pageInfo);
        }else{
            PageInfo<Object> pageInfo = new PageInfo<>(collect);
            pageInfo.setTotal(totalLength);
            return ResultGenerator.genOkResult(pageInfo);
        }
    }


    @Override
    public Result getPriceTable(String itemClassName, String itemCode) {
        HelpItemEnum helpItemEnum = HelpItemEnum.getHelpByName(itemClassName);
        String operationId = null;
        switch (helpItemEnum) {
            case ITEM_CLASS_EXAM:
                operationId = ConstantEnum.HZQUERY_10001.getKey();
                break;
            case ITEM_CLASS_LAB:
                operationId = ConstantEnum.HZQUERY_10002.getKey();
                break;
            case ITEM_CLASS_MANAGEMENT:
                operationId = ConstantEnum.HZQUERY_10003.getKey();
                break;
            case ITEM_CLASS_MATERIAL:
                operationId = ConstantEnum.HZQUERY_10004.getKey();
                break;
            case ITEM_CLASS_DRUG:
                operationId = ConstantEnum.HZQUERY_10005.getKey();
                break;
            default:
                return ResultGenerator.genFailedResult("没有此类项目的价表。");
        }
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        String empNo = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        String operationDate = DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm");
        String params = "{" +
                "    'operationID': '" + operationId + "'," +
                "    'c_request': {" +
                "       'request': {" +
                "            'source': '3'," +
                "            'hospital_no': ''," +
                "            'operator': '" + empNo + "'," +
                "            'operationdate': '" + operationDate + "'," +
                "            'item_code':'" + itemCode + "'" +
                "        }" +
                "    }" +
                "}";
        log.info("操作码:{}-{}", operationId, params);
        String resultString = HttpClientUtil.sendPostByJson(hisQueryUrl, params);
        log.info("操作码:{}-result-{}", operationId, resultString);
        JSONObject jsonObject = JSONObject.parseObject(resultString);
        if (!jsonObject.getString("Error_Id").equals(ConstantEnum.HIS_ERROR_CODE_1.getKey())) {
            return ResultGenerator.genFailedResult("查询出错：" + jsonObject.getString("Error_Msg"));
        }
        JSONObject response = jsonObject.getJSONObject("c_response").getJSONObject("response");
        return ResultGenerator.genOkResult(response);
    }


}
